package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.mongo.Movement;
import com.tanhua.vo.MovementsVo;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 分页查询用户
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        //分页查询用户
        IPage<UserInfo> iPage = userInfoApi.findAllUsers(page, pagesize);
        //显示用户冻结状态
        List<UserInfo> list = iPage.getRecords();
        for (UserInfo userInfo : list) {
            String key = Constants.FREEZE_USER + userInfo.getId();
            if(redisTemplate.hasKey(key)){
                userInfo.setUserStatus("2");
            }
        }
        //封装返回
        return new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 根据用户id查看用户详情
     *
     * @param userId
     * @return
     */
    public UserInfo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        //显示用户冻结状态
        String key = Constants.FREEZE_USER + userId;
        if(redisTemplate.hasKey(key)){
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }

    /**
     * 动态分页
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        PageResult pageResult = videoApi.findAllVideos(uid, page, pagesize);
        return pageResult;
    }

    /**
     * 分页查询动态
     *
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return
     */
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //1、调用API查询 ：（PageResult<Publish>）
        PageResult pageResult = movementApi.findById(uid, state, page, pagesize);
        //2、一个Publsh构造一个Movements
        List<Movement> items = (List<Movement>) pageResult.getItems();
        if (items == null || items.size() == 0) {
            return new PageResult();
        }
        //3、构造返回值
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        ArrayList<MovementsVo> list = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                list.add(vo);
            }
        }
        pageResult.setItems(list);
        return pageResult;
    }

    /**
     * 冻结用户
     * @param map
     * @return
     */
    public Map freeze(Map map) {
        //用户id
        Long userId = (Long) map.get("userId");
        //冻结时间
        Integer freezingTime = (Integer) map.get("freezingTime");
        //转化天数
        int days = freezingTime == 1 ? 3 : (freezingTime == 2 ? 7 : -1);
        //向redis存入冻结用户
        String key = Constants.FREEZE_USER+userId;
        String value = JSON.toJSONString(map);
        redisTemplate.opsForValue().set(key,value,days, TimeUnit.DAYS);
        //封装返回结果
        Map resMap = new HashMap();
        resMap.put("message","冻结成功");
        return resMap;
    }

    /**
     * 解冻用户
     * @param map
     * @return
     */
    public Map unfreeze(Map map) {
        //用户id
        Long userId = (Long) map.get("userId");
        //从redis中删除冻结数据
        String key = Constants.FREEZE_USER+userId;
        redisTemplate.delete(key);
        //封装返回结果
        Map resMap = new HashMap();
        resMap.put("message","解冻成功");
        return resMap;
    }
}
